package com.chx.service.Impl;

import com.chx.constant.MessageConstant;
import com.chx.dto.SupplierDto;
import com.chx.dto.SupplierPageQueryDto;
import com.chx.entity.Suppliers;
import com.chx.exception.DeletionNotAllowedException;
import com.chx.mapper.ProductMapper;
import com.chx.mapper.PurchaseOrderMapper;
import com.chx.mapper.SupplierMapper;
import com.chx.result.PageResult;
import com.chx.service.SupplierService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author cp-月入过万
 * @Date 2025/5/30
 */
@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductMapper  productMapper;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Override
    public void save(SupplierDto supplierDto) {
        Suppliers suppliers = new Suppliers();
        BeanUtils.copyProperties(supplierDto, suppliers);
        supplierMapper.insert(suppliers);
    }

    @Override
    public void update(SupplierDto supplierDto) {
        Suppliers suppliers = new Suppliers();
        BeanUtils.copyProperties(supplierDto, suppliers);
        supplierMapper.update(suppliers);
    }

    @Override
    public void delete(Long id) {
        // 判断是否有关联商品
        if(productMapper.getProductById(id)>0)
            throw new DeletionNotAllowedException(MessageConstant.DELETE_HAS_PRODUCT);
        // 应该判断 是否有订单关联
        if(purchaseOrderMapper.getProductById(id)>0)
             throw new DeletionNotAllowedException(MessageConstant.DELETE_HAS_ORDER);
        supplierMapper.delete(id);
    }

    @Override
    public Suppliers getById(Long id) {
        return supplierMapper.getById(id);
    }

    @Override
    public PageResult page(SupplierPageQueryDto supplierPageQueryDto) {
        PageHelper.startPage(supplierPageQueryDto.getPage(), supplierPageQueryDto.getPageSize());
        Page<Suppliers> page = supplierMapper.pageQuery(supplierPageQueryDto);
        long  total = page.getTotal();
        List<Suppliers> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    public List<Suppliers> getAllSuppliers() {
        return supplierMapper.getAllSuppliers();
    }
}
